package com.banciyuan.bcywebview.biz.detail;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.DailyApi;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.access.UserAccessHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.detail.atperson.AtPersonActivity;
import com.banciyuan.bcywebview.biz.detail.comment.CommentConstants;
import com.banciyuan.bcywebview.biz.post.uploadpic.IGetToken;
import com.banciyuan.bcywebview.biz.post.uploadpic.UploadPicHelper;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.PhotoModel;
import com.banciyuan.bcywebview.biz.write.photoselecotor.pselector.PhotoActivity;
import com.banciyuan.bcywebview.utils.anim.DeleteCommentAnimation;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.daoexample.model.ClearMulti;
import de.greenrobot.daoexample.model.DetailComment;
import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.Multi;

/**
 * Created by hy on 2015/6/1.
 */
public class EditActivity extends BaseActivity implements View.OnClickListener {
    public static final int GOATPERSON = 101;
    public static final int END_ADD = 1999;
    public final static int REQ_PIC = 1;

    private EditText etComment;
    private String srcContent;
    private String uname;
    private RequestQueue mQueue;
    private ImageView ivAt;
    private ImageView emoji;
    private TextView charge_tv;
    private TextView reply_back;
    private FlowView emoji_container;
    private ImageView comment_img;
    private ImageView comment_pic;
    private View img_container;
    private DetailType mDetailType;
    private ProgressBar mPostProgress;

    private int comment_type = 1;
    private boolean show_charge = false;
    private boolean isCommenting = false;
    private String comment_id;
    private int pos;
    private String hint;
    private String upload_src;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        initArgs();
        initUi();
        initEmoji();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        comment_type = intent.getIntExtra(CommentConstants.COMMENT_TYPE, 1);
        srcContent = intent.getStringExtra(CommentConstants.CONTENT);
        uname = intent.getStringExtra(CommentConstants.UNAME);
        show_charge = intent.getBooleanExtra(CommentConstants.SHOW_CHARGE, false);
        comment_id = intent.getStringExtra(CommentConstants.COMMENT_ID);
        pos = intent.getIntExtra(CommentConstants.COMMENT_POS, 0);
        hint = intent.getStringExtra(CommentConstants.COMMENT_HINT);
        mDetailType = new DetailType();
        DetailDataHelper.getBaseDetailVaule(mDetailType, intent);
        mQueue = VolleyQueue.getRquest(this);
    }

    private boolean canPostImg() {
        return UserAccessHelper.getReplyCommentAccess(this);
    }

    @Override
    protected void initUi() {
        etComment = (EditText) findViewById(R.id.et_comment);
        emoji = (ImageView) findViewById(R.id.comment_emoji);
        emoji_container = (FlowView) findViewById(R.id.emoji_container);
        charge_tv = (TextView) findViewById(R.id.feed_love);
        reply_back = (TextView) findViewById(R.id.reply_back);
        comment_img = (ImageView) findViewById(R.id.comment_reply_img);
        comment_pic = (ImageView) findViewById(R.id.comment_pic);
        img_container = findViewById(R.id.img_container);
        mPostProgress = (ProgressBar) findViewById(R.id.post_progress);
        ivAt = (ImageView) findViewById(R.id.iv_at);
        findViewById(R.id.tv_finish).setOnClickListener(this);
        findViewById(R.id.iv_cancle).setOnClickListener(this);
        comment_pic.setOnClickListener(this);
        comment_img.setOnClickListener(this);
        ivAt.setOnClickListener(this);
        emoji.setOnClickListener(this);
        switch (comment_type) {
            case 1:
                if (TextUtils.isEmpty(hint)) {
                    etComment.setHint(getString(R.string.want_comment));
                } else {
                    etComment.setHint(hint);
                }
                reply_back.setText(getString(R.string.post_comment));
                reply_back.setVisibility(View.VISIBLE);
                break;
            case 2:
                etComment.setHint(getString(R.string.comment_at) + uname + ":");
                reply_back.setText(getString(R.string.comment_at) + uname);
                reply_back.setVisibility(View.VISIBLE);
                break;
            case 3:
                etComment.setText(getString(R.string.dafult_pay_comment));
                reply_back.setVisibility(View.GONE);
                break;
            case 4:
                etComment.setHint(getString(R.string.comment_at) + uname + ":");
                reply_back.setText(getString(R.string.comment_at) + uname);
                reply_back.setVisibility(View.VISIBLE);
                break;
        }
        if (show_charge) {
            charge_tv.setVisibility(View.VISIBLE);
        }
        etComment.addTextChangedListener(new TextWatcher() {
            String preStr = "";
            String nowStr = "";

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                nowStr = s.toString();
                if ((nowStr.length() - preStr.length()) == 1) {
                    char lastChar = s.charAt(s.length() - 1);
                    if ('@' == lastChar) {
                        Intent intent = new Intent(EditActivity.this, AtPersonActivity.class);
                        startActivityForResult(intent, GOATPERSON);
                    }
                }
                preStr = nowStr;
            }
        });
    }

    private void showSoftInput(final EditText et) {
        et.requestFocus();
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(et, 0);
            }
        }, 200);
    }

    public void hideSoftKeyboard() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != inputManager && inputManager.isActive()) {
            inputManager.hideSoftInputFromWindow(etComment.getApplicationWindowToken(), 0);
        }
    }

    private void initEmoji() {
        String[] emojis = getResources().getStringArray(R.array.emoji);
        LayoutInflater inflater = LayoutInflater.from(EditActivity.this);
        for (int i = 0; i < emojis.length; i++) {
            final TextView single_emoji = (TextView) inflater.inflate(R.layout.emoji, null);
            single_emoji.setText(emojis[i]);
            single_emoji.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String text = ((TextView) view).getText().toString();
                    etComment.setText(etComment.getText().toString() + text);
                    etComment.setSelection(etComment.getText().length());
                    emoji_container.setVisibility(View.GONE);
                    showSoftInput(etComment);
                }
            });
            emoji_container.addView(single_emoji);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_finish:
                if (!isCommenting) {
                    isCommenting = true;
                    mPostProgress.setVisibility(View.VISIBLE);
                    if (TextUtils.isEmpty(upload_src)) {
                        if (TextUtils.isEmpty(etComment.getEditableText().toString())) {
                            MyToast.show(this, getString(R.string.input_empty_content));
                            isCommenting = false;
                            mPostProgress.setVisibility(View.GONE);
                        } else {
                            doComment(etComment.getEditableText().toString(), "");
                        }
                    } else {
                        String content = TextUtils.isEmpty(etComment.getEditableText().toString()) ?
                                getString(R.string.pic_comment) : etComment.getEditableText().toString();
                        doCommentWithPic(content);
                    }
                }
                break;
            case R.id.iv_cancle:
                onCancleBack();
                break;
            case R.id.iv_at:
                etComment.setText(etComment.getText().toString() + "@");
                etComment.setSelection(etComment.getText().length());
                break;
            case R.id.comment_emoji:
                if (emoji_container.getVisibility() == View.GONE) {
                    emoji_container.setVisibility(View.VISIBLE);
                    hideSoftKeyboard();
                } else {
                    emoji_container.setVisibility(View.GONE);
                    showSoftInput(etComment);
                }
                break;
            case R.id.comment_pic:
                if (canPostImg()) {
                    Intent intent = new Intent(this, PhotoActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, true);
                    startActivityForResult(intent, REQ_PIC);
                } else {
                    MyToast.show(this, getString(R.string.over_10_zan));
                }
                break;
            case R.id.comment_reply_img:
                hideImg();
                upload_src = "";
                break;
        }
    }

    private void hideImg() {
        if (img_container.getVisibility() != View.GONE) {
            DeleteCommentAnimation.setAnimation(img_container);
            img_container.postDelayed(new Runnable() {
                @Override
                public void run() {
                    img_container.setVisibility(View.GONE);
                }
            }, 200);
        }
    }

    private void showImg() {
        if (img_container.getVisibility() != View.VISIBLE) {
            img_container.setScaleX(1f);
            img_container.setScaleY(1f);
            img_container.setVisibility(View.VISIBLE);
        }
    }

    private void onCancleBack() {
        finish();
        setResult(RESULT_CANCELED);
        overridePendingTransition(R.anim.base_slide_left_in_quick, R.anim.base_slide_left_out_quick);
    }

    public void doCommentWithPic(final String content) {
        UploadPicHelper uploadPicHelper = new UploadPicHelper(this, new IGetToken() {
            @Override
            public void getTokenSucc(List<Multi> path) {
                List<ClearMulti> clearMultis = new ArrayList<>();
                for (Multi m : path) {
                    ClearMulti clearMulti = new ClearMulti();
                    clearMulti.parse(m);
                    clearMulti.setType("image");
                    clearMultis.add(clearMulti);
                }
                doComment(content, new Gson().toJson(clearMultis));
            }

            @Override
            public void getTokenFail() {
                mPostProgress.setVisibility(View.GONE);
            }
        }, true);
        List<PhotoModel> plist = new ArrayList<>();
        PhotoModel photoModel = new PhotoModel();
        photoModel.setOriginalPath(upload_src);
        plist.add(photoModel);
        int type = 0;
        if (comment_type == 2 || comment_type == 4) {
            type = 1;
        }
        switch (mDetailType.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                uploadPicHelper.getToken(type == 0 ? "ud_id" : "reply_id", type == 0 ? mDetailType.getUd_id() : comment_id, type == 0 ? DailyApi.getReplyUploadtoken() : DailyApi.getReplyCommentUploadtoken(), plist);
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                uploadPicHelper.getToken(type == 0 ? "post_id" : "reply_id", type == 0 ? mDetailType.getPost_id() : comment_id, type == 0 ? GroupApi.getReplyUploadtoken() : GroupApi.getReplyCommentUploadtoken(), plist);
                break;
            case TimelineFactory.TIMELINE_TYPE_COSER:
                uploadPicHelper.getToken(type == 0 ? "rp_id" : "reply_id", type == 0 ? mDetailType.getRp_id() : comment_id, type == 0 ? CoserApi.getReplyUploadtoken() : CoserApi.getReplyCommentUploadtoken(), plist);
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                uploadPicHelper.getToken(type == 0 ? "rp_id" : "reply_id", type == 0 ? mDetailType.getRp_id() : comment_id, type == 0 ? IllustApi.getReplyUploadtoken() : IllustApi.getReplyCommentUploadtoken(), plist);
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                uploadPicHelper.getToken(type == 0 ? "rp_id" : "reply_id", type == 0 ? mDetailType.getRp_id() : comment_id, type == 0 ? NovelApi.getReplyUploadtoken() : NovelApi.getReplyCommentUploadtoken(), plist);
                break;
        }
    }

    public void doComment(String content, String multi) {
        if (comment_type == 1 || comment_type == 3) {
            doCommentTask(content, multi);
        } else if (comment_type == 2) {
            doReplyComment(comment_id, content, multi);
        } else if (comment_type == 4) {
            doReplyComment(comment_id, String.format(MyConstants.COMMENT_FORMAT, uname, content), multi);
        }
    }

    private void doReplyComment(String reply_id, String content, String multi) {
        String url = "";
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.COMMENT_ID, reply_id));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.DAILY_CONTENT, content));
        if (!TextUtils.isEmpty(multi)) {
            paramsList.add(new BcyPair(HttpUtils.MULTI, multi));
        }
        switch (mDetailType.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url = HttpUtils.BASE_URL + IllustApi.publishReplyComment();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                paramsList.add(new BcyPair(HttpUtils.DPID, mDetailType.getDp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url = HttpUtils.BASE_URL + CoserApi.publishReplyComment();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                paramsList.add(new BcyPair(HttpUtils.CPID, mDetailType.getCp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url = HttpUtils.BASE_URL + DailyApi.publishReplyComment();
                paramsList.add(new BcyPair(HttpUtils.UDID, mDetailType.getUd_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                url = HttpUtils.BASE_URL + GroupApi.publishReplyComment();
                paramsList.add(new BcyPair(HttpUtils.POSTID, mDetailType.getPost_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url = HttpUtils.BASE_URL + NovelApi.publishReplyComment();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                paramsList.add(new BcyPair(HttpUtils.WPID, mDetailType.getWp_id()));
                break;
        }
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, EditActivity.this)) {
                    try {
                        DetailComment detailComment = new Gson().fromJson(new JSONObject(response).getString(HttpUtils.UPLOAD_DATA), DetailComment.class);
                        etComment.setText("");
                        Intent intent = new Intent();
                        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, detailComment);
                        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, pos);
                        setResult(END_ADD, intent);
                        finish();
                        overridePendingTransition(R.anim.base_slide_left_in_quick, R.anim.base_slide_left_out_quick);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                mPostProgress.setVisibility(View.GONE);
                isCommenting = false;
            }
        };
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mPostProgress.setVisibility(View.GONE);
                isCommenting = false;
            }
        };
        Map<String, String> map = HttpUtils.getData(paramsList);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
    }

    private void doCommentTask(final String content, String multi) {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, EditActivity.this)) {
                    try {
                        DetailComment detailComment = new Gson().fromJson(new JSONObject(response).getString(HttpUtils.UPLOAD_DATA), DetailComment.class);
                        MyToast.show(EditActivity.this, getString(R.string.comment_succ));
                        etComment.setText("");
                        Intent intent = new Intent();
                        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, detailComment);
                        setResult(END_ADD, intent);
                        finish();
                        overridePendingTransition(R.anim.base_slide_left_in_quick, R.anim.base_slide_left_out_quick);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                mPostProgress.setVisibility(View.GONE);
                isCommenting = false;
            }
        };
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mPostProgress.setVisibility(View.GONE);
                isCommenting = false;
            }
        };
        doComment(onSuccess, onError, content, multi);
    }

    private Boolean doComment(Response.Listener<String> onSuccess,
                              Response.ErrorListener onError, String content, String multis) {

        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        String url = "";
        switch (mDetailType.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
            case TimelineFactory.TIMELINE_TYPE_COSER:
            default:
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                if (!TextUtils.isEmpty(mDetailType.getCp_id())) {
                    paramsList.add(new BcyPair(HttpUtils.CPID, mDetailType.getCp_id()));
                    url = HttpUtils.BASE_URL + CoserApi.getDoreply();
                } else {
                    paramsList.add(new BcyPair(HttpUtils.DPID, mDetailType.getDp_id()));
                    url = HttpUtils.BASE_URL + IllustApi.getDoreply();
                }
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                paramsList.add(new BcyPair(HttpUtils.UDID, mDetailType.getUd_id()));
                url = HttpUtils.BASE_URL + DailyApi.getDoreply();
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                paramsList.add(new BcyPair(HttpUtils.POSTID, mDetailType.getPost_id()));
                url = HttpUtils.BASE_URL + GroupApi.getDoreply();
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                paramsList.add(new BcyPair(HttpUtils.WPID, mDetailType.getWp_id()));
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                url = HttpUtils.BASE_URL + NovelApi.getDoreply();
                break;
        }
        paramsList.add(new BcyPair(HttpUtils.REPLY_PTYPE, "2"));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.UPLOAD_DATA, content));
        if (!TextUtils.isEmpty(multis)) {
            paramsList.add(new BcyPair(HttpUtils.MULTI, multis));
        }
        Map<String, String> map = HttpUtils.getData(paramsList);
        StringRequestParam getUserdataRequest = new StringRequestParam(
                Request.Method.POST, url, map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
        return true;
    }

    @Override
    public void onBackPressed() {
        onCancleBack();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GOATPERSON) {
            if (resultCode == RESULT_OK) {
                String personname = data.getStringExtra("personname");
                if (!TextUtils.isEmpty(personname)) {
                    etComment.setText(etComment.getText().toString() + personname);
                    etComment.setSelection(etComment.getText().length());
                }
            } else {
                if (emoji_container.getVisibility() == View.VISIBLE) {
                    hideSoftKeyboard();
                }
            }
        } else if (requestCode == REQ_PIC) {
            try {
                String filepath = data.getExtras().getString("path");
                if (!TextUtils.isEmpty(filepath)) {
                    File pic = new File(filepath);
                    if (pic.exists()) {
                        showImg();
                        upload_src = filepath;
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 4;
                        comment_img.setImageBitmap(BitmapFactory.decodeFile(upload_src, options));
                        showSoftInput(etComment);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
